package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.service.MyorderService;
import com.chixing.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("ali")
public class AliPayController {
    @Autowired
    private MyorderService myorderService;

    // 1. 支付：调用支付宝支付
    @PostMapping("pay")
    @ResponseBody
    public String pay(String orderId,String productName,Float myorderPrice){
        System.out.println("============================================");
        System.out.println("orderId:" + orderId);
        System.out.println("productName:" + productName);
        System.out.println("myorderPrice:" + myorderPrice);

//       OrderProductVO orderProductVO =  myorderService.getByOrderId(orderId);
     //(1)初始化AlipayClient
     AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                                                            AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                                                            AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
    //(2)设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("http://127.0.0.1:8080/zyx/ali/alipayReturnNotice"); // 同步请求支付
//        alipayRequest.setNotifyUrl("http://127.0.0.1:8080/zyx/myorder/myorder_center.jsp"); // 异步请求支付




   //(3)支付请求中的订单信息 --- alirequest  context
        String out_trade_no = orderId.replace(" ","").replaceAll("\r|\n","");

         Float total_amount = myorderPrice;
        String subject = productName;
        String body = "";
        String timeout_express = "30m";    // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。


        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String payResult = null;
        try {
            AlipayResponse alipayResponse =  alipayClient.pageExecute(alipayRequest);

            System.out.println("pay code:"+ alipayResponse.getCode());
            System.out.println("pay getSubCode:"+ alipayResponse.getSubCode());
            System.out.println("pay getMsg:"+ alipayResponse.getMsg());
            System.out.println("pay isSuccess:"+ alipayResponse.isSuccess());  //支付成功后返回true
            payResult =  alipayResponse.getBody();// getBody() 支付后，支付宝返回的支付的信息
            System.out.println("支付宝返回的支付的信息：" + payResult);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return  payResult;
    };

    // 支付后的 获得 支付宝的信息 payResult --->request
    @RequestMapping("alipayReturnNotice")
    public String returnNotice(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        System.out.println("同步返回页面操作。。。。。");
//        int custId = (int)request.getSession().getAttribute("custId");
        ModelAndView mav = new ModelAndView("myorder/myorder_center");
//        mav.addObject("custId",custId);
        Map<String, String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
            System.out.print(name);
            System.out.print(":");
            System.out.println(valueStr);
        }
        String out_trade_no = params.get("out_trade_no");
//        System.out.println("======================================================out_trade_no:" + out_trade_no);
        myorderService.updateByMyorderNo(out_trade_no);
        myorderService.createFlow(out_trade_no);
        System.out.println(">>>>>支付后的 获得 支付宝的信息 " + params ); //>>>>>支付后的 获得 支付宝的信息 org.apache.catalina.util.ParameterMap@62df00ea
//        return mav;
        return "redirect:/myorder/" + out_trade_no;
    }



    @GetMapping("alipayNotifyNotice")
    @ResponseBody
    public String notifyNotice(HttpServletRequest request,HttpServletResponse response){
        System.out.println("异步返回页面操作。。。。。");
        Map<String,String[]> map= request.getParameterMap();
        System.out.println("支付后的 获得 支付宝的信息 " + map);
        Iterator<Map.Entry<String, String[]>> iterator = map.entrySet().iterator();
        return "alipaySuccess";
    }
}



